//
//  ChangeHeaderPortraitViewController.m
//  WHB_logist
//
//  Created by 徐国庆 on 15/12/7.
//  Copyright (c) 2015年 turing. All rights reserved.
//

#import "ChangeHeaderPortraitViewController.h"
#import <CoreMedia/CMFormatDescription.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "CTAssetsPickerController.h"
#import "VPImageCropperViewController.h"

@interface ChangeHeaderPortraitViewController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CTAssetsPickerControllerDelegate, VPImageCropperDelegate>

@property(nonatomic, strong) UIImagePickerController  *pickerCamera;
@property(nonatomic, strong) CTAssetsPickerController *ctapicker;
@property(nonatomic, strong) NSString                 *imageName;//上传图片名称

@end

@implementation ChangeHeaderPortraitViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setTabBarHidden];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self showTabBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navtitle.text = @"修改头像";
    [self initWithView];
}

- (void)changeButtonAction:(UIButton *)button{
    UIActionSheet *SheetMenu = [[UIActionSheet alloc] initWithTitle:@"请选择"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"摄像头拍照",@"从相册选择", nil];
    [SheetMenu showInView:self.view];
}

#pragma mark ActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    
    if ([title isEqualToString:@"摄像头拍照"]){
        if (_pickerCamera == nil){
            _pickerCamera = [[UIImagePickerController alloc] init];
            _pickerCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
            [_pickerCamera setCameraCaptureMode:UIImagePickerControllerCameraCaptureModePhoto];
            _pickerCamera.delegate = self;
        }
        [self presentViewController:_pickerCamera animated:YES completion:^{
            if (IsIOS7) {
                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authStatus != AVAuthorizationStatusAuthorized){
                    PXAlertView *alertview = [PXAlertView showAlertWithTitle:@"系统提示" message:@"请打开设置隐私相机允许访问" cancelTitle:@"确 认" completion:nil];
                    [alertview useDefaultIOS7Style];
                    return;
                }
            }
        }];
    }
    else if([title isEqualToString:@"从相册选择"]){
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [self selectPhoto:btn];
    }
}


//选择照片
-(void)selectPhoto:(id)sender
{
    _ctapicker=[[CTAssetsPickerController alloc]init];
    _ctapicker.delegate=self;
    _ctapicker.showsNumberOfAssets=YES;
    _ctapicker.assetsFilter=[ALAssetsFilter allPhotos];
    
    UIImageView *navbar = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kNavHeight)];
    navbar.image = [UIImage imageNamed:@"jian"];
    navbar.image = [navbar.image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [_ctapicker.navigationController.navigationBar setBackgroundImage:navbar.image forBarMetrics:UIBarMetricsDefault];
    [_ctapicker.childNavigationController.navigationBar setBackgroundImage:navbar.image forBarMetrics:UIBarMetricsDefault];
    //设置左右按钮文字颜色
    _ctapicker.childNavigationController.navigationBar.tintColor = [UIColor whiteColor];
    //设置标题文字颜色
    _ctapicker.childNavigationController.navigationBar.titleTextAttributes=[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    [self.navigationController presentViewController:_ctapicker animated:YES completion:nil];
}


#pragma mark - CTAssetsPickerControllerDelegate  选图片代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    UIImage *newImage;
    for (ALAsset *ass in assets) {
        
        ALAssetRepresentation *representation = ass.defaultRepresentation;
        UIImage *originImage =[UIImage imageWithCGImage:representation.fullResolutionImage scale:representation.scale orientation:(UIImageOrientation)representation.orientation];
        CGFloat width = 900;
        CGFloat height = originImage.size.height/originImage.size.width * width;
        //压缩后新图
        newImage=[UtilsHelper imageWithImageSize:originImage scaledToSize:CGSizeMake(width, height)];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openCropper:newImage];
    }];
}

#pragma mark 设置最多允许选择的数量
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(ALAsset *)asset
{
    return picker.selectedAssets.count < 1;
}

#pragma mark ImagePickerDelegate 拍照后调用
-(void)imagePickerController:(UIImagePickerController *)pickerMy didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])
    {
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        CGFloat width = 900;
        CGFloat height = originImage.size.height/originImage.size.width * width;
        //压缩后新图
        UIImage *newImage=[UtilsHelper imageWithImageSize:originImage scaledToSize:CGSizeMake(width, height)];
        [pickerMy dismissViewControllerAnimated:YES completion:^{
            [self openCropper:newImage];
        }];
    }
}

#pragma mark OSS上传图片
-(void)osstest:(UIImage*)image
{
    //生成图片名称
    _imageName = [NSString stringWithFormat:@"headImg/%@.png",kIdentifierString];
    // 上传
    /*
    [HttpEngine ossuploadimage:image fullimageName:_imageName uploadCallback:^(BOOL isSuccess, NSError *error) {
        
        if (isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.8)];
                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                
                //设置头像
                NSString *fullImageName = [NSString stringWithFormat:@"%@%@%@",aliyunOSSIMGURL,_imageName,[UIAdapterHelper returnHeadImageSize]];
                [_btnPhoto sd_setImageWithURL:[NSURL URLWithString:fullImageName] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"Headshop"]];
                //设置模糊背景
                [_headerbackground sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", fullImageName, @"_30-30bl_-25b"]] placeholderImage:[UIImage imageNamed:@"bg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                }];
            });
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.8)];
                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传"];
            });
        }
        
    } withProgressCallback:^(float progressFloat) {
        [SVProgressHUD showProgress:progressFloat status:@"正在上传"];
    }];
     */
}

#pragma mark 图片裁切
-(void)openCropper:(UIImage*)selsectImg{
    
    VPImageCropperViewController *imgCropper = [[VPImageCropperViewController alloc] initWithImage:selsectImg cropFrame:CGRectMake(0, 100.0f, kUIScreenWidth, kUIScreenWidth) limitScaleRatio:3.0];
    imgCropper.delegate = self;
    [self presentViewController:imgCropper animated:YES completion:nil];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    //裁切图片后上传
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        [self osstest:editedImage];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController{
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)commitButtonAction:(UIButton *)button{
    
}

- (void)initWithView{
    UIButton *changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    changeButton.frame = CGRectMake((kUIScreenWidth - 100) / 2, kNavHeight + 50, 100, 100);
    [changeButton setImage:[UIImage imageNamed:@"tx"] forState:UIControlStateNormal];
    changeButton.layer.masksToBounds = YES;
    changeButton.layer.cornerRadius = 50;
    [changeButton addTarget:self action:@selector(changeButtonAction:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:changeButton];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, changeButton.frame.origin.y + changeButton.frame.size.height + 50, kUIScreenWidth, 0.5)];
    lineLabel.backgroundColor = [UIColor HexStrWithColor:@"BEBEBE"];
    [self.view addSubview:lineLabel];
    
    UIButton *commitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    commitButton.frame = CGRectMake(10, lineLabel.frame.origin.y + lineLabel.frame.size.height + 20, kUIScreenWidth - 20, 35);
    [commitButton setTitle:@"提交修改" forState:UIControlStateNormal];
    commitButton.backgroundColor = [UIColor HexStrWithColor:@"CE0000"];
    commitButton.layer.masksToBounds = YES;
    commitButton.layer.cornerRadius = 5;
    [self.view addSubview:commitButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
